//
//  BBGHttpRespParser.swift
//  Test
//
//  Created by 钟志远 on 2020/4/1.
//  Copyright © 2020 alyadan. All rights reserved.
//

import Foundation
import YD_NetworkModule
import Alamofire
import RxSwift
import RxCocoa
import SwiftyJSON

class BBGHttpRespParser: HTTPRespParserType {
    var paramsDealBlock: ((Parameters?) -> Parameters?)?
    var responseDealBlock: ((Parameters?) -> Parameters?)?
    
    func httpRequest(httpMethod: HTTPMethod, url: String, param: Parameters?, baseUrl: URL?, header: HTTPHeaders?) -> Observable<YDNetworkSuccessResp> {
        
        
        return Observable.create({ (dataObserver:AnyObserver) -> Disposable in
            
            if url == "NULL" {
                dataObserver.onError(YDNetworkError.paramError)
                return Disposables.create()
            }
            
            guard let escapedURLString = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let resultUrl = URL(string: escapedURLString, relativeTo: baseUrl ?? URL.init(string: "")) else {
                dataObserver.onError(YDNetworkError.paramError)
                return Disposables.create()
            }
            
            let req = request(resultUrl, method: httpMethod, parameters: param, headers: header).responseJSON { (response) in
                switch response.result{
                case .success(let value):
                    let jsonValue = JSON(value)
                    guard let errorCode  = jsonValue["status"].int else {
                        dataObserver.onError(YDNetworkError.responseDataError)
                        return
                    }
                    
                    guard errorCode == 0 else {
                        dataObserver.onError(YDNetworkError.serverError(url: url, param: param,msg: jsonValue["message"].stringValue, code: errorCode))
                        return
                    }
                    
                    guard let data = jsonValue["data"].object as? [String: Any] else {
                        dataObserver.onError(YDNetworkError.responseDataError)
                        return
                    }
                    
                    dataObserver.onNext((data, jsonValue.dictionary))
                    dataObserver.onCompleted()
                case .failure(let err):
                    dataObserver.onError(YDNetworkError.connectError(url: url, param: param, error: err))
                }
                
            }
            
            let dispose = Disposables.create(with: {
                req.cancel()
            })
            
            return dispose
        })
            //            .retry(2)
            .share(replay: 1)
    }
    
    
}
